import request from '@/utils/request';
import { useUserStore } from '@/stores/user';

/**
 * 创建订单
 * @param data 订单数据
 * @returns Promise
 */
export function createOrder(data: any) {
    const userStore = useUserStore();
    const userId = userStore.userInfo?.id;
    return request.post('/orders', data, { params: { userId } });
}

/**
 * 获取买家订单列表
 * 订单状态:
 * - 不传/undefined: 全部
 * - 1: 待交易
 * - 4: 待评价
 * - 2: 已完成
 * - 3: 已取消
 */
export function fetchBuyerOrders(params: any) {
    const userStore = useUserStore();
    const userId = userStore.userInfo?.id;
    return request.get('/orders/buyer', { params: { ...params, userId } });
}

/**
 * 获取卖家订单列表
 * 订单状态同上
 */
export function fetchSellerOrders(params: any) {
    const userStore = useUserStore();
    const userId = userStore.userInfo?.id;
    return request.get('/orders/seller', { params: { ...params, userId } });
}

// 获取订单详情
export function getOrderDetail(orderId: number) {
    const userStore = useUserStore();
    const userId = userStore.userInfo?.id;
    return request.get(`/orders/${orderId}`, { params: { userId } });
}

// 确认收货
export function confirmReceipt(orderId: number) {
    const userStore = useUserStore();
    const userId = userStore.userInfo?.id;
    return request.post(`/orders/${orderId}/confirm`, {}, { params: { userId } });
}

// 取消订单
export function cancelOrder(orderId: number, data: any) {
    const userStore = useUserStore();
    const userId = userStore.userInfo?.id;
    // 从data中移除userId，防止请求体中也包含
    const { userId: _, ...requestData } = { ...data, userId };
    return request.post(`/orders/${orderId}/cancel`, requestData, { params: { userId } });
}

// 创建订单评价
export function createOrderReview(orderId: number, data: any) {
    const userStore = useUserStore();
    const userId = userStore.userInfo?.id;
    // 从data中移除userId，防止请求体中也包含
    const { userId: _, ...reviewData } = { ...data, userId };
    return request.post(`/orders/${orderId}/reviews`, reviewData, { params: { userId } });
}

// 获取订单评价
export function getOrderReview(orderId: number) {
    const userStore = useUserStore();
    const userId = userStore.userInfo?.id;
    return request.get(`/orders/${orderId}/reviews`, { params: { userId } });
} 